#!/usr/bin/env python


#this script submits the jobs now as array jobs, works only if first file if 1, but that could be changed

#import sys, os, os.path, cx_Oracle
import sys, os, os.path, mysql

if not (len(sys.argv) == 8 or len(sys.argv) == 9):
        print 'cl_make_and_load.db  <username> <password> <cluster: True|False> <update mysql db: True|False> <update mysql db with failed ligs: True|False> <project> <path to scripts> <file with smarts> (only for pattern matching)'
        sys.exit(1)


username = sys.argv[1]
password = sys.argv[2]
cluster = sys.argv[3]
update_db = sys.argv[4]
update_failed = sys.argv[5]
project = sys.argv[6]
script_path = sys.argv[7]
if len(sys.argv)==9:
	smarts_file = sys.argv[8]
	pattern_matching = True
else:
	pattern_matching = False



if cluster == 'True':
	cluster = True
else:
	cluster = False

if update_db == 'True':
	update_db = True
else:
	update_db = False

if update_failed == 'True':
	update_failed = True
else:
	update_failed = False

if update_failed or update_db: #check that passwords are correct

	#check db connection
	conn=mysql.connect2server(password, username,'purchasable')  
	cursor = conn.cursor ()

	#check project
	command = 'select unique_compounds, supplier_info_table, supplier_table from projects where project = "' + project + '"'
	#print command
	cursor.execute(command)
	results=cursor.fetchall()
	if len(results) == 0:
		print 'project does not exist'
		sys.exit(1)
	conn.close()

needed_scripts = ['make_and_load_db.py', 'superpos_conf_ensemble.py', 'mysql_load_dockable.py', 'amsol.py']

#check that files exist

if not os.path.exists('omega.single'):
	if os.path.exists(script_path +  'omega.single'):
		command = 'cp ' + script_path +  'omega.single .'
		print command
		os.system(command)
	else:
		print 'omega.single does not exist'
		sys.exit()
if not os.path.exists('omega.mult'):
	if os.path.exists(script_path +  'omega.mult'):
		command = 'cp ' + script_path +  'omega.mult .'
		os.system(command)
	else:
		print 'omega.mult does not exist'
		sys.exit()
if not os.path.exists('inhier'):
	if os.path.exists(script_path +  'inhier'):
		command = 'cp ' + script_path +  'inhier .'
		os.system(command)
	else:
		print 'inhier does not exist'
		sys.exit()

for script in needed_scripts:
	if not os.path.exists(script_path + script):
		print script, ' does not exist'	
		sys.exit()
	
#make some needed directoryies
if not os.path.exists('omega_mult'):
	os.makedirs('omega_mult')
if not os.path.exists('solv'):
	os.makedirs('solv')
if not os.path.exists('errors'):
	os.makedirs('errors')	
if not os.path.exists('input_smiles'):
	os.makedirs('input_smiles')	

if not update_db and  not os.path.exists('new_dbs'):
	os.makedirs('new_dbs')

#get all *smi files

files = os.listdir('./')
files.sort()

clean_list = []

#remove all none .smi from files
for i in files:
	if i[-4:] == '.smi':
		#print i
		clean_list.append(i)
		start = i.rfind('_') + 1 #rfind -> last occurance of sub string

files = clean_list


for i in files:
	   #test format of label, must be MFCxxxxxxxxx
	   tmp_smi = open(i, 'r')
	   label_list = []
	   for line in tmp_smi.readlines():
		MFC_start = line.find('MFC')
		if MFC_start <> -1:
			label = line[MFC_start:-1]
			if len(label) <> 12:
				#wrong format
				print 'wrong label format, must be MFCxxxxxxxxx'
				sys.exit()
			else:
				if label in label_list:
					#wrong format
					print 'duplicate label', label
					sys.exit()			
				else:
					label_list.append(label)		
		else:
				#wrong format
				print 'wrong label format, must be MFCxxxxxxxxx'
				sys.exit()
	   tmp_smi.close()
	   break #one test should be enough

if cluster:

	for i in files:

		file_name = i[:-4] + '_start.bin'
		start_file = open(file_name, 'w')
		start_file.write("#BSUB-q short             	# Job queue\n#BSUB-o job.output              # output is sent to file job.output\n#BSUB-J test_mogon              # name of the job\n")

		start_file.write(script_path + '/make_and_load_db.py')
		start_file.write(username + ' ' + password + ' ' + i + ' True ' + str(update_db) + ' ' + str(update_failed) +  ' ' + project + ' ' + script_path)
		if pattern_matching:
			start_file.write(' ' + smarts_file)
		start_file.close()
		os.system('chmod 744 '  + file_name)
		command = 'qsub -q long ' + file_name
		print command
		os.system(command)

else:
	for i in files:
		command = script_path + "make_and_load_db.py "  + username + ' ' + password + ' ' + i + ' False ' + str(update_db) + ' ' + str(update_failed) + ' ' + project + ' ' + script_path
		if pattern_matching:
			command = command + ' ' + smarts_file

	   	print command
	   	os.system(command)


